﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IsmsExplorer.Infrastructure.DomainBase;
using IsmsExplorer.Infrastructure.EntityFactoryFramework.Configuration;
using System.Configuration;
using System.Diagnostics;

namespace IsmsExplorer.Infrastructure.EntityFactoryFramework {
    public static class EntityFactoryBuilder<T> where T : EntityBase {
        // A cache of the factories - essentially singletons, in order to avoid having to recreate.
        // Maps short type name (or entity) to the actual factory object.
        static Dictionary<string, object> _factories = new Dictionary<string, object>();

        public static IEntityFactory<T> BuildFactory<T>() where T : EntityBase {
            IEntityFactory<T> factory = default(IEntityFactory<T>);
            // Get the short type name, acting as a id to create factory.
            string entityShortTypeName = typeof(T).Name;
            // If factory exists, return cached object, else create a new one, cache it and return to caller.
            if (_factories.ContainsKey(entityShortTypeName)) {
                factory = _factories[entityShortTypeName] as IEntityFactory<T>;

            } else {
                EntitySettings settings = (EntitySettings) ConfigurationManager.GetSection(EntityMappingConstants.EntityMappingsConfigurationSectionName);
                Type t = Type.GetType(settings.EntityMapping[entityShortTypeName].EntityFactoryFullTypeName);
                factory = Activator.CreateInstance(t) as IEntityFactory<T>;
                Debug.Assert(factory != null, "Entity factory created from type is null");
                _factories[entityShortTypeName] = factory;
            }
            return factory;
        }
    }
}
